﻿using CJAtech.BBS.Business;
using CJAtech.BBS.DataEntity;
using CJAtech.Weplatform.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Bigger.Base;
using Bigger.Framework;
using Bigger.Base.Cache;
using System.Threading;
using CJAtech.BBS.Process;
using CJAtech.BBS.Web.Models;
using Bigger.Web.Helper;

namespace CJAtech.BBS.Web.Controllers
{
    /*
    1、缺详情页
    2、缺评论分页
    */

    public partial class GuangQiController : BaseController
    {
        public ActionResult DemoHtml()
        {
            return View();
        }

        /// <summary>
        /// BBS首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文章列表
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult ArticleListHtml(int? page = 1)
        {
            if (!page.HasValue || page <= 0)
            {
                page = 1;
            }
            BizArticleInfo objBizArticleInfo = new BizArticleInfo();
            return View(objBizArticleInfo.GetPageList(page.Value - 1, 10, "", "SortIndex desc"));
        }
        /// <summary>
        /// 文章详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Detail(int? id)
        {
            if (!id.HasValue)
            {
                return Http404();
            }
            BizArticleInfo objBizArticleInfo = new BizArticleInfo();
            //ArticleInfo objArticleInfo = objBizArticleInfo.GetRecordCache(id.Value);
            ArticleInfo objArticleInfo = objBizArticleInfo.GetRecord(id.Value);
            if (objArticleInfo == null)
            {
                return Http404();
            }
            ArticleResultInfo objArticleResultInfo = new ArticleResultInfo();
            objArticleResultInfo.ArticleInfo = objArticleInfo;
            BizArticleInfoData objBizArticleInfoData = new BizArticleInfoData();
            ArticleInfoData objArticleInfoData = objBizArticleInfoData.GetRecord("ArticleId =" + objArticleInfo.ArticleId + " AND InfoDataType=@InfoDataType", new { InfoDataType = ArticleInfoDataType.ArticleContent });
            if (objArticleInfoData != null)
            {
                objArticleResultInfo.ArticleContent = objArticleInfoData.ArticleContent;
            }
            InvokeResult objInvokeResult = CheckUserTicket("tjzheng");
            if (objInvokeResult.ResultCode != "Success")
            {
                return Http404();
            }
            HttpContext.SetItems("UserInfo", objInvokeResult.Data);
            return View(objArticleResultInfo);
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddComment(int? id, string content)
        {

            InvokeResult objInvokeResult = new InvokeResult();
            if (!id.HasValue)
            {
                objInvokeResult.ResultCode = "IDEmpty";
                objInvokeResult.ResultMessage = "对不起，文章不存在";
                return Json(objInvokeResult);
            }
            if (content.IsNull())
            {
                objInvokeResult.ResultCode = "ContentEmpty";
                objInvokeResult.ResultMessage = "对不起，内容不能为空";
                return Json(objInvokeResult);
            }
            objInvokeResult = CheckUserTicket("tjzheng");
            if (objInvokeResult.ResultCode != "Success")
            {
                return Json(objInvokeResult);
            }

            UserInfo objUserInfo = objInvokeResult.Data as UserInfo;
            var CurrentCache = Bigger.Core.Cache.CacheHelper.CacheInstance;

            //获取上一次评论缓存
            CommentInfo objLastCommentInfo = CurrentCache.GetCache<CommentInfo>("LastComment_" + objUserInfo.UserId);
            if (objLastCommentInfo != null && objLastCommentInfo.CreateDate.AddSeconds(5).IsGreaterThanCurrent())
            {
                objInvokeResult.ResultCode = "CommentFrequently";
                objInvokeResult.ResultMessage = "对不起，请你与上次评论间隔5秒";
                return Json(objInvokeResult);
            }

            CommentInfo objCommentInfo = new CommentInfo()
            {
                ObjectId = id.Value.ToString(),
                ObjectCode = "Article_" + id,
                UserId = objUserInfo.UserId,
                NickName = objUserInfo.UserName,
                Content = content,
                IsAudit = 1,
                UserIP = SystemWebAsset.GetClientIP(),
                CreateDate = DateTime.Now
            };
            BizCommentInfo objBizCommentInfo = new BizCommentInfo();
            objInvokeResult.ResultMessage = "评论成功";
            objInvokeResult.Data = objBizCommentInfo.Add(objCommentInfo);

            //设置上一条评论缓存
            CurrentCache.SetCache("LastComment_" + objUserInfo.UserId, objCommentInfo, TimeSpan.FromSeconds(10));
            return Json(objInvokeResult);
        }

        /// <summary>
        /// 评论点赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DiggComment(int? id, int? articleId)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (!id.HasValue)
            {
                objInvokeResult.ResultCode = "IDEmpty";
                objInvokeResult.ResultMessage = "对不起，评论不存在";
                return Json(objInvokeResult);
            }
            if (!articleId.HasValue)
            {
                objInvokeResult.ResultCode = "ArticleIdEmpty";
                objInvokeResult.ResultMessage = "对不起，文章不存在";
                return Json(objInvokeResult);
            }
            objInvokeResult = CheckUserTicket("tjzheng");
            if (objInvokeResult.ResultCode != "Success")
            {
                return Json(objInvokeResult);
            }
            BizCommentInfo objBizCommentInfo = new BizCommentInfo();
            CommentInfo objCommentInfo = objBizCommentInfo.GetRecord(id.Value);
            if (objCommentInfo == null)
            {
                objInvokeResult.ResultCode = "CommentInfoEmpty";
                objInvokeResult.ResultMessage = "对不起，评论不存在";
                return Json(objInvokeResult);
            }
            BizDiggInfo objBizDiggInfo = new BizDiggInfo();
            UserInfo objUserInfo = objInvokeResult.Data as UserInfo;
            bool hasDigg = objBizDiggInfo.Any("UserId=@UserId AND ObjectId=@ObjectId AND ObjectCode=@ObjectCode", new { UserId = objUserInfo.UserId, ObjectId = id.Value, ObjectCode = "Article_" + articleId });
            if (hasDigg)
            {
                objInvokeResult.ResultCode = "DiggAlready";
                objInvokeResult.ResultMessage = "对不起，你已对该评论点赞过";
                return Json(objInvokeResult);
            }
            DiggInfo objDiggInfo = new DiggInfo
            {
                ObjectId = id.Value.ToString(),
                ObjectCode = "Article_" + articleId,
                UserId = objUserInfo.UserId,
                UserIP = SystemWebAsset.GetClientIP(),
                DiggTime = DateTime.Now
            };
            objBizDiggInfo.Add(objDiggInfo);
            //更新评论点赞
            objCommentInfo.DiggCount = objCommentInfo.DiggCount + 1;
            objBizCommentInfo.Update("DiggCount=" + objCommentInfo.DiggCount, objCommentInfo.CommentId);
            objInvokeResult.ResultMessage = "点赞成功";
            return Json(objInvokeResult);
        }


        /// <summary>
        /// 中转地址
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public ActionResult TargetUrl(string openId)
        {
            BizTargetInfo objBizTargetInfo = new BizTargetInfo();
            TargetInfo objTargetInfo = objBizTargetInfo.GetRecord(1);
            if (objTargetInfo == null || objTargetInfo.TargetUrl.IsNull())
            {
                return Http404();
            }
            InvokeResult objInvokeResult = SetUserTicket(openId, "tjzheng");
            if (objInvokeResult.ResultCode != "Success")
            {
                return Content("对不起，您登录超时");
            }
            return Redirect(objTargetInfo.TargetUrl);
        }

        /// <summary>
        /// 检查票据
        /// </summary>
        /// <param name="secret"></param>
        /// <returns></returns>
        [NonAction]
        public InvokeResult CheckUserTicket(string secret)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            string openId = CookieHelper.GetCookieValue("UserId");
            if (openId.IsNull())
            {
                objInvokeResult.ResultCode = "OpenIdNull";
                objInvokeResult.ResultMessage = "对不起，您登录超时";
                return objInvokeResult;
            }
            string userName = CookieHelper.GetCookieValue("UserName");
            if (userName.IsNull())
            {
                objInvokeResult.ResultCode = "UserNameNull";
                objInvokeResult.ResultMessage = "对不起，您登录超时";
                return objInvokeResult;
            }
            var ticket = CookieHelper.GetCookieValue("Ticket_" + openId);
            if (ticket.IsNull())
            {
                objInvokeResult.ResultCode = "TicketNull";
                objInvokeResult.ResultMessage = "对不起，您的登录票据已失效";
                return objInvokeResult;
            }
            string checkTicket = openId.EncodeMD5(secret);
            if (!string.Equals(checkTicket, ticket))
            {
                objInvokeResult.ResultCode = "TicketError";
                objInvokeResult.ResultMessage = "对不起，您的登录票据信息有误";
                return objInvokeResult;
            }
            objInvokeResult.ResultMessage = "登录成功";
            objInvokeResult.Data = new UserInfo
            {
                UserId = openId,
                UserName = userName
            };
            return objInvokeResult;
        }
        /// <summary>
        /// 设置票据
        /// </summary>
        /// <param name="openId">用户标识</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        [NonAction]
        public InvokeResult SetUserTicket(string openId, string secret)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (openId.IsNull())
            {
                objInvokeResult.ResultCode = "OpenIdNull";
                return objInvokeResult;
            }
            BizUser objBizUser = new BizUser();
            var objUser = objBizUser.GetRecord("openid=@openid", new { openid = openId });
            if (objUser == null)
            {
                objInvokeResult.ResultCode = "UserNull";
                return objInvokeResult;
            }
            CookieHelper.SetCookieValue(openId, "UserId");
            CookieHelper.SetCookieValue(objUser.Nickname, "UserName");
            string ticket = objUser.Openid.EncodeMD5(secret);
            CookieHelper.SetCookieValue(ticket, "Ticket_" + objUser.Openid);
            return objInvokeResult;
        }
    }
}
